# Contributor: Mehdi Chinoune <mehdi.chinoune@hotmail.com>

if [[ $MINGW_PACKAGE_PREFIX == *-clang-* ]]; then
  _clangprefix=1
fi

_realname=polly
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=13.0.0
pkgrel=3
pkgdesc="Polly - Polyhedral optimizations for LLVM (mingw-w64)"
url="https://polly.llvm.org/"
arch=(any)
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32' 'clangarm64')
license=("custom:Apache 2.0 with LLVM Exception")
groups=($( (( _clangprefix )) && echo "${MINGW_PACKAGE_PREFIX}-toolchain"))
depends=("${MINGW_PACKAGE_PREFIX}-llvm")
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-python-sphinx")
options=('!debug' 'strip')
_url=https://github.com/llvm/llvm-project/releases/download/llvmorg-${pkgver}
_pkgfn=$_realname-$pkgver.src
source=($_url/$_pkgfn.tar.xz{,.sig})
sha256sums=('cd93672c3be35146e199b1e221fb81a39403a0cdeabcad4a47ae878655eea872'
            'SKIP')
validpgpkeys=('B6C8F98282B944E3B0D5C2530FC3042E345AD05D'  # Hans Wennborg, Google.
              '474E22316ABF4785A88C6E8EA2C794A986419D8A') # Tom Stellard

build() {
  cd ${srcdir}
  [[ -d build-${MSYSTEM} ]] && rm -rf build-${MSYSTEM}
  mkdir -p build-${MSYSTEM} && cd build-${MSYSTEM}

  if check_option "debug" "y"; then
    _build_type="Debug"
  else
    _build_type="Release"
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  cmake \
    -GNinja \
    -DCMAKE_BUILD_TYPE=${_build_type} \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DCMAKE_SYSTEM_IGNORE_PATH=/usr/lib \
    -DLLVM_HOST_TRIPLE="${CARCH}-w64-windows-gnu" \
    -DPython3_EXECUTABLE=${MINGW_PREFIX}/bin/python.exe \
    -DPython3_FIND_REGISTRY=NEVER \
    -DPython3_ROOT_DIR=${MINGW_PREFIX} \
    -DLLVM_ENABLE_SPHINX=ON \
    -DLLVM_LINK_LLVM_DYLIB=ON \
    -Wno-dev \
    ../$_pkgfn

  cmake --build .
}

package() {
  DESTDIR=${pkgdir} cmake --install build-${MSYSTEM}

  # fix cmake files.
  local PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  local SRC_WIN=$(cygpath -wm ${srcdir})
  sed -e "s|${PREFIX_WIN}|${MINGW_PREFIX}/|g" \
    -e "s|${SRC_WIN}/build-${MSYSTEM}/lib|${MINGW_PREFIX}/lib|g" \
    -i "${pkgdir}/${MINGW_PREFIX}/lib/cmake/polly/PollyConfig.cmake"

  install -d "$pkgdir${MINGW_PREFIX}"/share/licenses/${_realname}
  install -Dm644 $_pkgfn/LICENSE* -t "$pkgdir${MINGW_PREFIX}"/share/licenses/${_realname}
}
